<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    :ctype="type"
    :okText="t('确认')"
    @register="registerModal"
    @ok="handleSubmit"
    :minHeight="300"
    :width="500"
    :showOkBtn="false"
    :showCancelBtn="false"
  >
    <div class="ml-4 mt-4">
      <a-textarea
        v-model:value="inputRef"
        :placeholder="`请扫描${placeholder}(鼠标聚焦到当前位置)`"
        style="height: 250px; width: 450px"
        ref="ainput"
      />
      <a-row :gutter="[16, 16]" style="margin-top: 20px; height: 30px">
        <a-col :span="24">
          <div v-if="tips == '扫码成功' || tips == '数据校验通过！'">
            <p class="tips-success">{{ tips }}</p>
          </div>
          <div v-else>
            <p class="tips-error">{{ tips }}</p>
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="[16, 16]" style="margin-top: 15px">
        <a-col :span="5" :offset="14">
          <a-button type="error" @click="clearText('1')">重新扫描</a-button>
        </a-col>
        <a-col :span="5">
          <a-button type="success" @click="endScan()">结束扫描</a-button>
        </a-col>
      </a-row>
    </div>
  </BasicModal>

  <!-- 批量退料登记 -->
  <BatchTl @register="registerBatchTl" @success="handleSuccess" />
  <!-- 半成品退料登记 -->
  <WhBatchTl @register="registerWhBatchTl" @success="handleSuccess" />
</template>
<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { useDrawer } from '/@/components/Drawer';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { extdBillImportData } from '/@/api/extd/bill/extdBill';
  import globalSetting from '/@/enums/globalSetting';

  import BatchTl from '/@/views/asd/tl/batchTl.vue';
  import WhBatchTl from '/@/views/wh/tl/batchTl.vue';

  import { BarCodeCheck } from '/@/api/asd/barcode/barcode';

  const emit = defineEmits(['success', 'register']);
  const { t } = useI18n('extd.bill.extdBill');
  const { showMessage, showMessageModal, createConfirm } = useMessage();

  let placeholder = ref<string>('');
  const fileList = ref([]);
  const enterCount = ref(0);
  let inputRef = ref<string>('');
  let ainput = ref<any>(null);
  // const url = data;
  let url = ref<any>(null);
  let title = ref<any>(null);
  let type = ref<any>(null);
  console.log('type', type);

  let queryData = {
    userCode: '',
    picId: '',
    funcType: '',
    venCode: '',
    cusCode: '',
  };

  let flowIds = ref<any>([]);

  let checkData = ref<any>({});

  // 提示信息
  let tips = ref<string>('');

  const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
    type.value = data.type;
    if (type.value == '0') {
      placeholder.value = '现品票'; //退料申请
    }
    flowIds.value = [];
    enterCount.value = 0;
    inputRef.value = '';
    tips.value = '';
    queryData = {
      cbarcode: '',
    };
    url.value = data.url;
    title.value = data.title;
    type.value = data.type;
    ainput.value.focus();
    // fileList.value = [];
  });

  // 批量检验
  const [registerBatchTl, { openDrawer: openDrawerBatchTl }] = useDrawer();
  const [registerWhBatchTl, { openDrawer: openDrawerWhBatchTl }] = useDrawer();

  function onUploadProgress(progressEvent: ProgressEvent) {
    const complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
    if (complete != 100) {
    } else {
    }
  }

  // 清空内容
  function clearText(flag) {
    inputRef.value = '';
    enterCount.value = 0;
    ainput.value.focus();
    queryData.cbarcode = '';
    if (flag == 1) {
      tips.value = '';
    }
  }

  // 结束扫描
  async function endScan() {
    let lines = inputRef.value.split(/\n+/);
    lines.forEach((item, index) => {
      // 删除空项
      if (item === '') {
        lines.splice(index, 1);
      }
    });
    ainput.value.blur();

    let barArr = lines.filter((item) => {
      return item;
    });

    if (type.value == globalSetting.workScanEnum.TL) {
      if (barArr.length == 0) {
        tips.value = '现品票为空!';
        return false;
      }
      const res = await BarCodeCheck({ cbarcode: barArr.join(',') });
      if (res.result == 'true') {
        openDrawerBatchTl(true, res);
        tips.value = '';
      } else {
        tips.value = res.message;
      }
      return false;
    } else if (type.value == globalSetting.workScanEnum.whTL) {
      if (barArr.length == 0) {
        tips.value = '现品票为空!';
        return false;
      }
      const res = await BarCodeCheck({ cbarcode: barArr.join(',') });
      if (res.result == 'true') {
        console.log(res, 'res');
        res.list.forEach((item) => {
          // item.xppNo: item.xppNo,
          console.log(item.xppNo, 'item');
          item.xppno = item.xppNo;
        });
        openDrawerWhBatchTl(true, res);
        // openDrawerBatchTl(true, res);
        tips.value = '';
      } else {
        tips.value = res.message;
      }
      return false;
    } else {
      clearText('');
      tips.value = '请重新扫码!';
      return false;
    }
  }

  async function handleSubmit() {
    try {
      if (fileList.value.length == 0) {
        showMessage(t('请选择要导入的数据文件'));
        return;
      }
      setModalProps({ confirmLoading: true });
      const params = {
        file: fileList.value[0],
      };
      const { data } = await extdBillImportData(params, onUploadProgress);
      showMessageModal({ content: data.message });
      setTimeout(closeModal);
      emit('success');
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 保存成功回调
  function handleSuccess() {
    setTimeout(() => {
      clearText('');
      ainput.value.focus();
    }, 500);
  }
</script>

<style scoped>
  .ant-btn-error {
    /* margin-right: 10px; */
    float: right;
  }
  .ant-input {
    background: url(/@/assets/icons/scan-icon/bg.png) 370px 170px no-repeat;
    z-index: auto;
  }

  .tips-success {
    color: green;
    font-size: 18px;
  }

  .tips-error {
    color: red;
    font-size: 18px;
  }
</style>
